package com.sgb.net.core;

import android.text.TextUtils;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.List;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author: 杨畔
 * @date: 2021/2/22 09:06
 * @Description: 拦截器，更换baseUrl用
 */
public class UrlInterceptor implements Interceptor {

    public static final String BASE_URL = "BASE_URL";
    //初始地址段数，例如https://www.sgb.net/path0/path1/...后面的path0和path1
    public static final String REDUNDANT_PATH_SEGMENT_SIZE = "REDUNDANT_PATH_SEGMENT_SIZE";
    //默认分段
    private final int mPathSegmentSize;

    public UrlInterceptor() {
        this(0);
    }

    public UrlInterceptor(int mPathSegmentSize) {
        this.mPathSegmentSize = mPathSegmentSize;
    }

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder builder = request.newBuilder();
        //拦截retrofit注解的header配置信息
        List<String> list = request.headers(BASE_URL);
        if (!list.isEmpty()) {
            //移除掉header 因为服务器不需要这个header
            builder.removeHeader(BASE_URL);
            //需要移除的多余分段
            List<String> pathSegmentSizeList = request.headers(REDUNDANT_PATH_SEGMENT_SIZE);
            int pathSegmentSize = mPathSegmentSize;
            if (!pathSegmentSizeList.isEmpty()) {
                //移除掉header 因为服务器不需要这个header
                builder.removeHeader(REDUNDANT_PATH_SEGMENT_SIZE);
                pathSegmentSize = convertToInt(pathSegmentSizeList.get(0), mPathSegmentSize);
            }
            //获取到设置的url
            String url = list.get(0);
            HttpUrl newBaseUrl = HttpUrl.get(url);
            HttpUrl oldBaseUrl = request.url();
            //将旧的请求地址里的协议、域名、端口号替换成配置的请求地址
            HttpUrl.Builder newFullBuilder = oldBaseUrl.newBuilder()
                    .scheme(newBaseUrl.scheme())
                    .host(newBaseUrl.host())
                    .port(newBaseUrl.port());
            //移除baseurl多余分段
            if (pathSegmentSize > 0) {
                for (int i = 0; i < pathSegmentSize; i++) {
                    newFullBuilder.removePathSegment(0);
                }
            }
            //build新链接
            HttpUrl newFullUrl = newFullBuilder.build();
            //创建带有新地址的新请求
            Request newRequest = builder.url(newFullUrl).build();
            return chain.proceed(newRequest);
        }
        return chain.proceed(builder.build());
    }

    /**
     * 设置新url，部分接口切换地址用，在@Headers注释中使用
     *
     * @param url 新rul
     */
    public static String newUrl(String url) {
        return String.format("%s:%s", BASE_URL, url);
    }

    private int convertToInt(String number, int defaultValue) {
        if (TextUtils.isEmpty(number)) {
            return defaultValue;
        }
        try {
            return Integer.parseInt(number);
        } catch (Exception e) {
            return defaultValue;
        }
    }
}
